package com.ssca.postgresql;

import java.io.Reader;
import java.util.*;
import java.util.Map.Entry;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.ssca.mysql.ReadMysql;
import com.ssca.mysql.category.InitialUtils;

public class WriteAppInfo {

	public static void writeAppInfo() {
		Reader reader;
		try {
			reader = Resources.getResourceAsReader("MybatisConfig.xml");
			SqlSessionFactoryBuilder ssfBuilder = new SqlSessionFactoryBuilder();
			SqlSessionFactory sqlSessionFactory = ssfBuilder.build(reader, "postgresql");
			SqlSession sqlSession = sqlSessionFactory.openSession();
			AppInfoDAO appinfoDAO = sqlSession.getMapper(AppInfoDAO.class);
			AppCategoryDAO appCategory = sqlSession.getMapper(AppCategoryDAO.class);

			Map<String, Integer> downloadNumberMap = new HashMap<String, Integer>();
			Map<String, String> categoryMap = new HashMap<String, String>();

			ReadMysql.readDownload(downloadNumberMap, categoryMap);
			categoryMap = InitialUtils.initial(categoryMap);
			for (Entry<String, Integer> en : downloadNumberMap.entrySet()) {
				String pkgName = en.getKey();
				int downloadNumber = en.getValue();
				String category = categoryMap.get(pkgName);
				Integer categoryID = appCategory.selectAppCategoryID(category);
				if (categoryID == null) {
					appCategory.insertAppCategory(category);
					categoryID = appCategory.selectAppCategoryID(category);
					sqlSession.commit();
				}

				// 判断pkg是否已经存在于AppInfo中
				Integer number = appinfoDAO.selectAppInfo(pkgName);
				if (number == null) {
					// pkgName不存在于AppInfo，执行insert操作
					appinfoDAO.insertAppInfo(pkgName, downloadNumber, categoryID);
				} else {
					// pkgName已存在，执行update操作
					appinfoDAO.updateAppInfo(pkgName, downloadNumber, categoryID);
				}
				sqlSession.commit();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// private static Integer select(String pkgName){
	// Integer downloadNumber = null ;
	// Reader reader;
	// try {
	// reader = Resources.getResourceAsReader("MybatisConfig.xml");
	// SqlSessionFactoryBuilder ssfBuilder = new SqlSessionFactoryBuilder();
	// SqlSessionFactory sqlSessionFactory =
	// ssfBuilder.build(reader,"postgresql");
	// SqlSession sqlSession = sqlSessionFactory.openSession();
	// AppInfoDAO aliasesDAO = sqlSession.getMapper(AppInfoDAO.class);
	//
	// downloadNumber = aliasesDAO.selectAppInfo(pkgName);
	// System.out.println(downloadNumber);
	// }catch (Exception e){
	// e.printStackTrace();
	// }
	//
	// return downloadNumber;
	// }
}
